﻿using AutoMapper;
using HelenServer.FileStorage.Contracts;
using HelenServer.Grpc.Contracts;

namespace HelenServer.FileStorage.Services;

[Injection(typeof(IFSNotifySpider))]
public class FSNotifySpider : GrpcMethod<NotifySpiderGrpcModel, GrpcResult<int>>, IFSNotifySpider
{
    private readonly IFileStorageService _service;
    private readonly IMapper _mapper;
    private readonly HttpClient _httpClient;

    public FSNotifySpider(IFileStorageService fileStorage, IMapper mapper, IHttpClientFactory factory)
    {
        _service = fileStorage;
        _mapper = mapper;
        _httpClient = factory.CreateClient("client");
    }

    public override async Task<GrpcResult<int>> InvokeAsync(NotifySpiderGrpcModel request, ServerCallContext context)
    {
        var spider = _mapper.Map<NotifySpiderGrpcModel, NotifySpiderModel>(request);

        _httpClient.DefaultRequestHeaders.Add("Authorization", context.RequestHeaders.GetString("zt_authorization"));

        var buffer = await _httpClient.GetByteArrayAsync(spider.Url, context.CancellationToken);

        var model = new UploadModel
        {
            Name = spider.Name,
            Extension = spider.Extension,
            AddedBy = spider.AddedBy,
            Buffer = buffer,
        };

        var operation = context.GetHttpContext().GetOperation(model);

        var result = await _service.UploadFileAsync(operation, context.CancellationToken);

        return result.ToGrpcResult(r => r);
    }
}